#!/bin/sh
# +++ Parameter Start +++
# . CommonBuildLib.sh action
# 1,action 指定要进行的动作.
# === Parameter End ===

# +++ Description Start +++
# CommonBuildLib.sh
# 按照给定的变量,执行编译操作.
# === Description End ===

# 如果放在函数里面,就变成函数的参数了.
compileAction=$1

doClean() {
    echo "\n+ clean start +"

    if [[ -e "${g_sourceLibDir}/makefile" ]]; then
        echo "distclean"
        make -C ${g_sourceLibDir} distclean
    fi

    if [[ -e "makefile" ]]; then
        echo "clean"
        make clean
        [[ $? != 0 ]] && echo "- clean failed -" && exit
    else
        echo "No need to clean"
    fi
    echo "= clean end ="
}

# configure做的事情:
# 1 设置makefile需要的一些环境变量,根据架构的不同,可能不同.
# 2 配置configure的flag,根据架构的不同,可能不同.
# 3 configure,得到makefile文件.
# 根据要编译出来的ffmpeg的功能,设置ffempg,这里希望能够代码播放flv.
doConfigure() {
    # 在build目录下执行源码目录中的configure命令,中间文件在build目录下.
    ${g_sourceLibDir}/configure ${g_flag}
}

doMake() {
    rm -rf ${outputLibDir}
    make -j4
    make install
}

main() {
    echo "\n\n\n+++ Build ${g_libId} for ${g_platform} with ${g_arch},mode $g_compileMode,start  +++"
    [[ $compileAction == "" ]] && echo "no action specified" && exit
    # 切换到build临时目录
    cd ${g_buildLibDir}
    if [[ $compileAction == $COMPILE_ACTION_CONFIGURE_MAKE || $compileAction == $COMPILE_ACTION_CONFIGURE ]]; then
        echo "\n+ configure start +"
        if [[ $(type -t customConfigure) == "function" ]]; then
            customConfigure
        else
            doClean
            doConfigure
        fi
        [[ $? != 0 ]] && echo "configure failed" && exit
        echo "= configure end =\n\n\n"

    else
        echo "No need to configure."
    fi

    if [[ $(type -t afterConfigure) == "function" ]]; then
        afterConfigure
    fi

    if [[ $compileAction == $COMPILE_ACTION_CONFIGURE_MAKE || $compileAction == $COMPILE_ACTION_MAKE ]]; then
        echo "\n+ ${g_libId} make start +"
        if [[ $(type -t customMake) == "function" ]]; then
            customMake
        else
            doMake
        fi
        [[ $? != 0 ]] && echo "${g_libId} make failed" && exit
        echo "= ${g_libId} make end =\n"
        
    else
        echo "No need to make."
    fi

    if [[ $(type -t doFinish) == "function" ]]; then
        doFinish
    fi

    echo "=== Build ${g_libId} for ${g_platform} with ${g_arch} finish ===\n\n\n"
}

main
